import { defineEventHandler, getHeader, readBody } from 'h3'
import { adminRoutes } from '../admin-routes-store'
import redis from '../util/redis'

export default defineEventHandler(async (event) => {
  const key = getHeader(event, 'x-admin-key') || ''
  if (!key) {
    return { status: 401, message: 'Unauthorized: missing x-admin-key' }
  }

  const body = await readBody(event)
  if (!body || !body.path) {
    return { status: 400, message: 'Invalid body: need { path, allowed }' }
  }

  try {
    const data = adminRoutes
    const idx = data.routes.findIndex((r: any) => r.path === body.path)
    if (idx === -1) {
      data.routes.push({ path: body.path, allowed: !!body.allowed })
    } else {
      data.routes[idx].allowed = !!body.allowed
    }

    // persist to redis (best-effort). If redis isn't configured, this will throw and be caught.
    try {
      await redis.set('admin:routes', JSON.stringify(data))
    } catch (e) {
      // ignore redis set errors; still return updated in-memory data
    }

    return { status: 200, data }
  } catch (e) {
    return { status: 500, message: String(e) }
  }
})
